<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }

        .line {
            border: 2px solid green;
        }
    </style>
</head>

<body>
    <div id="box"></div>

    <script>
        let box = document.getElementById("box");
        // 鼠标按下事件
        box.onmousedown = function () {
            box.classList.add("line");
            // 鼠标移动事件
            window.onmousemove = function () {
                box.style.left = event.clientX - box.offsetWidth / 2 + "px";
                box.style.top = event.clientY - box.offsetHeight / 2 + "px";
            
                // 不能超出可视窗口
                // 水平方向
                if(box.offsetLeft<=0){
                    box.style.left=0;
                }else if(box.offsetLeft>=innerWidth-box.offsetWidth){
                    box.style.left=innerWidth-box.offsetWidth+"px";
                }
                
                // 垂直方向
                if(box.offsetTop<=0){
                    box.style.top=0;
                }else if(box.offsetTop>=innerHeight-box.offsetHeight){
                    box.style.top=innerHeight-box.offsetHeight+"px";
                }

            }
        }

        // 鼠标抬起事件
        box.onmouseup = function () {
            box.classList.remove("line");
            // 停止盒子移动
            window.onmousemove =null;
        }
    </script>
</body>

</html>